package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/sys_user")
@Slf4j
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 用户列表-分页
     *
     * @param login_name
     * @param status
     * @param phone
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String login_name, String status, String phone, Long page, Long limit) {
        log.info("login_name = {},status = {},phone = {},page = {},limit = {}", login_name, status, phone, page, limit);

        //定义页面构造器
        Page<SysUser> userPage = new Page<>(page, limit);
        Page<SysUserInfo> userInfoPage = new Page<>();
        //定义条件构造器
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        //判断是否注入条件
        lqw.like(StringUtils.isNotBlank(login_name), SysUser::getLoginName, login_name);
        lqw.like(StringUtils.isNotBlank(phone), SysUser::getPhone, phone);
        lqw.eq(StringUtils.isNotBlank(status), SysUser::getStatus, status);

        lqw.orderByDesc(SysUser::getCreateDate);
        //查询页面信息
        sysUserService.page(userPage, lqw);
        //复制页面
        BeanUtils.copyProperties(userPage, userInfoPage, "records");
        //添加职位id和职位名称
        List<SysUser> records = userPage.getRecords();
        List<SysUserInfo> collect1 = records.stream().map((item) -> {
            //返回对象类型
            SysUserInfo sysUserInfo = new SysUserInfo();
            //复制信息
            BeanUtils.copyProperties(item, sysUserInfo);
            LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //获取职位id，把test类型转化为string，去掉[]和""
            String strip = StringUtils.strip(item.getRoleId(), "[]");
            String[] split = strip.split(",");
            for (int i = 0; i < split.length; i++) {
                split[i] = StringUtils.replace(split[i], "\"", "");
            }
            System.out.println(split);
            roleLambdaQueryWrapper.in(SysRole::getId, split);
            List<SysRole> list = roleService.list(roleLambdaQueryWrapper);
            //获取查询出来的职位id
            List<String> collect2 = list.stream().map((item2 -> {
                return item2.getId();
            })).collect(Collectors.toList());
            //获取查询出来的职位名称
            List<String> collect = list.stream().map((item1) -> {
                return item1.getName();
            }).collect(Collectors.toList());
            //赋值
            sysUserInfo.setRole_id(collect2);
            sysUserInfo.setRolename(collect);
            return sysUserInfo;
        }).collect(Collectors.toList());
        //赋值records
        userInfoPage.setRecords(collect1);
        //返回查询信息
        return ResultData.ok("查询成功", PageResult.init(userInfoPage.getTotal(), page, limit, userInfoPage.getRecords()));
    }

    /**
     * 管理员删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(String id) {
        log.info("id={}", id);
        //判断用户状态和权限
        SysUser sysUser = sysUserService.getById(id);
        //是否为系统默认数据
        if (("1".equals(sysUser.getDefaultData()))) {
            return ResultData.error("系统默认数据，无法删除");
        }
        //状态是否为启动
        if (sysUser.getStatus() == 1) {
            return ResultData.error("用户状态为启用,无法删除");
        }
        if (roleService.RoleUtils("系统设置","用户管理","删除")){
        sysUserService.removeById(id);
        return ResultData.ok("删除成功", "删除成功");
        }
        //否则没有权限删除
        return ResultData.error("删除失败，该用户没有权限");
    }

    /**
     * 管理员添加
     *
     * @param map
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody HashMap<String, Object> map) {
        log.info("map={}", map);
        SysUser sysUser = new SysUser();
        String login_name = (String) map.get("login_name");
        sysUser.setLoginName(login_name);
        String password = (String) map.get("password");
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(password);
        String phone = (String) map.get("phone");
        sysUser.setPhone(phone);
        String name = (String) map.get("name");
        sysUser.setName(name);
        String email = (String) map.get("email");
        sysUser.setEmail(email);
        Integer status = (Integer) map.get("status");
        sysUser.setStatus(status);
        ArrayList<String> role_id = (ArrayList<String>) map.get("role_id");
        String role_menus = "[";
        for (int i = 0; i < role_id.size(); i++) {
            if (i < role_id.size() - 1) {
                role_menus += "\"" + role_id.get(i) + "\"" + ",";
            } else {
                role_menus += "\"" + role_id.get(i) + "\"" + "]";
            }
        }
        sysUser.setRoleId(role_menus);
        sysUser.setCreateDate(LocalDateTime.now());
        if (roleService.RoleUtils("系统设置","用户管理","增加")){
        sysUserService.save(sysUser);
        return ResultData.ok("添加成功", "添加成功");
        }
        //否则没有权限添加
        return ResultData.error("添加失败,无权限添加!");
    }

    /**
     * 管理员详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        SysUserInfo sysUserInfo = new SysUserInfo();
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setPassword("******");
        String role_id = sysUser.getRoleId();
        List<String> list = new ArrayList<>();
        String strip = StringUtils.strip(role_id, "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i] = StringUtils.replace(split[i], "\"", "");
            list.add(split[i]);
        }
        BeanUtils.copyProperties(sysUser, sysUserInfo, "role_id");
        sysUserInfo.setRole_id(list);
        sysUserInfo.setPassword("");

        return ResultData.ok("查询成功", sysUserInfo);
    }

    /**
     * 管理员修改
     *
     * @param map
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody HashMap<String, Object> map) {
        String id = (String) map.get("id");
        SysUser sysUser = sysUserService.getById(id);
        if (map.get("login_name")!=null) {
            String login_name = (String) map.get("login_name");
            sysUser.setLoginName(login_name);
        }
        String password = (String) map.get("password");
        if (StringUtils.isNotBlank(password)) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            sysUser.setPassword(password);
        }
        if (map.get("phone")!=null) {
            String phone = (String) map.get("phone");
            sysUser.setPhone(phone);
        }
        if (map.get("name") != null) {
            String name = (String) map.get("name");
            sysUser.setName(name);
        }
        if (map.get("email") != null) {
            String email = (String) map.get("email");
            sysUser.setEmail(email);
        }
        Integer status = (Integer) map.get("status");
        sysUser.setStatus(status);
        ArrayList<String> role_id = (ArrayList<String>) map.get("role_id");
        if (role_id != null) {
            String role_menus = "[";
            for (int i = 0; i < role_id.size(); i++) {
                if (i < role_id.size() - 1) {
                    role_menus += "\"" + role_id.get(i) + "\"" + ",";
                } else {
                    role_menus += "\"" + role_id.get(i) + "\"" + "]";
                }
            }
            sysUser.setRoleId(role_menus);
        }
        sysUser.setUpdateDate(LocalDateTime.now());

        if (roleService.RoleUtils("系统设置","用户管理","更新")){
        sysUserService.updateById(sysUser);
        return ResultData.ok("更新成功", "更新成功");
        }

        //否则没有权限添加
        return ResultData.error("更新失败,无权限更新!");
    }


}
